import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router'
import { qiankunWindow } from 'vite-plugin-qiankun/dist/helper'
import AppLayout from '../layouts/AppLayout.vue'
import HomePage from '../views/HomePage.vue'
import CloudStorageConfig from '../views/CloudStorageConfig.vue'

// 获取qiankun环境下的基础路由
const getBasePath = () => {
  return qiankunWindow.__POWERED_BY_QIANKUN__ ? '/app1' : '/'
}

// 路由配置
const routes: Array<RouteRecordRaw> = [
  {
    path: '/',
    component: AppLayout,
    children: [
      {
        path: '',
        name: 'home',
        component: HomePage,
        meta: { title: '首页' }
      },
      {
        path: 'cloud-storage',
        name: 'cloud-storage',
        component: CloudStorageConfig,
        meta: { title: '云存储配置' }
      },
      {
        path: 'data-list',
        name: 'data-list',
        component: () => import('../views/DataListView.vue'),
        meta: { title: '数据列表' }
      },
      {
        path: 'user-management',
        name: 'user-management',
        component: () => import('../views/DataFormView.vue'),
        meta: { title: '用户管理' }
      },
      {
        path: 'permission-management',
        name: 'permission-management',
        component: () => import('../views/PermissionManagementView.vue'),
        meta: { title: '权限管理' }
      },
      {
        path: 'ai-model-config',
        name: 'ai-model-config',
        component: () => import('../views/AIModelConfigView.vue'),
        meta: { title: '大模型API配置' }
      },
      {
        path: 'app-config',
        name: 'app-config',
        component: () => import('../views/AppConfigView.vue'),
        meta: { title: '应用配置管理' }
      },
      {
        path: 'settings',
        name: 'settings',
        component: () => import('../views/GlobalConfigView.vue'),
        meta: { title: '全域配置' }
      },
      {
        path: 'reports',
        name: 'reports',
        component: () => import('../views/OrderManagementView.vue'),
        meta: { title: '订单管理' }
      },
      {
        path: 'gray-release',
        name: 'gray-release',
        component: () => import('../views/GrayReleaseView.vue'),
        meta: { title: '灰度名单管理' }
      },
      {
        path: 'data-analysis',
        name: 'data-analysis',
        component: () => import('../views/DataAnalysisView.vue'),
        meta: { title: '数据分析' }
      }
    ]
  }
]

// 创建路由实例
const router = createRouter({
  history: createWebHistory(getBasePath()),
  routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
  // app1不包含登录页面，直接放行所有路由
  // 在qiankun环境中，认证由base应用管理
  // 在独立环境中，通过Token管理工具进行调试
  next()
})

// 路由切换时自动设置document.title
router.afterEach((to) => {
  const appName = 'app1';
  const baseTitle = '应用管理系统';
  const pageTitle = to.meta?.title as string || String(to.name || '');
  const fullTitle = pageTitle ? `${pageTitle} - ${baseTitle}` : baseTitle;
  
  // 直接设置document.title，这将在独立运行时生效
  document.title = fullTitle;
  
  // 如果在微前端环境中，通知基座应用
  if (qiankunWindow.__POWERED_BY_QIANKUN__) {
    // 使用自定义事件通知基座应用，实现低耦合通信
    try {
      // 创建自定义事件，包含必要的标题信息
      const titleChangeEvent = new CustomEvent('micro-app-title-change', {
        detail: {
          title: pageTitle,
          fullTitle: fullTitle,
          appName: appName,
          path: to.fullPath
        }
      });
      
      // 在window上派发事件，基座应用可以监听此事件
      window.dispatchEvent(titleChangeEvent);
    } catch (e) {
      console.error('[App1] Failed to dispatch title change event:', e);
    }
  }
})

export default router 